<template>
	<view class="bg-f">
		<uni-drawer @jihuo="jihuo" :user_money="userinfo['user_money']" :malock="ma_lock" :memu="memu" :foxtel="userinfo['user_name']" :visible="showLeft" mode="left" @close="closeDrawer('left')"></uni-drawer>
		<!-- 顶部菜单 star-->				
		<view class="is-nav">
			<view class="is-nav-li is-nav-user" @click="show('left')">
				<image src="../../static/img/common/user.png"></image>
			</view>
			<view class="is-nav-li is-center is-blue is-active">
				OTC接单
			</view>
			<view class="is-nav-li is-center is-grey">
				<text @tap="ordering">进行中</text>
			</view>
			<view class="is-nav-li is-size-14 is-online" :class="[online === false ? 'is-red-color is-bold' : 'is-blue']">
				{{online === false ? '离线' : '在线'}}
			</view>
		</view>	
		<view class="has-pd-10 s-row">
			<view class="is-size-14 is-col-14">
				您的可用余额：<text class="is-red-color">{{user_money_can}}DC</text>
			</view>
			<view class="is-col-10 is-size-12 is-right is-grey">
				今日走单：<text class="is-bold">{{today_num}}</text>
			</view>
		</view>
		<view class="has-pdlr-10 has-pdb-5 s-row is-bg-wf">
			<view class="is-col-4 is-size-12 is-red-color">
				<text class="is-bold">{{you_chose}}</text>
			</view>
			<view class="is-col-5 is-size-12 is-grey is-center">
				WX:<text class="is-bold">{{today_num_wx}}</text>
			</view>
			<view class="is-col-5 is-size-12 is-grey is-center">
				ZFB:<text class="is-bold">{{today_num_zfb}}</text>
			</view>
			<view class="is-col-5 is-size-12 is-grey is-center">
				QQ:<text class="is-bold">{{today_num_qq}}</text>
			</view>
			<view class="is-col-5 is-size-12 is-grey is-center">
				BANK:<text class="is-bold">{{today_num_bank}}</text>
			</view>
			
		</view>
		<min-switch :desc="mycity" v-model="onlymecity" ></min-switch>
		<view class="pd-bottome">
			<view class="has-pd-20 s-row ma-order" v-for="(item,index) in order" :key="index">
				<view class="is-col-6 is-left ma-box">
					<image :src="ma_type_img" mode=""></image>
				</view>
				<view class="is-col-12">
					<view class="is-bold">{{item.out_trade_no}}</view>
					<view class="is-grey">￥{{item.total_fee_true}}</view>
				</view>
				<view class="is-col-6 is-right" @tap="grab(item.id,index)">
					<view class="pie">
					  <view class="pie-inner">
					  抢单
					  </view>
					</view>
				</view>
			</view>
			<view v-if="showLoader">
				<mht-loader loadingType="ball-pulse"></mht-loader>
			</view>
		</view>
		
		<view class="is-foot has-bg-white">
			<view class="has-pdtb-10 has-pdlr-20">
				<view class="has-floatl is-size-18 has-mgt-10">
					<view class="is-left is-blue-color">
						接单中
						<view class="spinner">
						    <view class="bounce1"></view>
						    <view class="bounce2"></view>
						    <view class="bounce3"></view>
						</view>
					</view>
				</view>
				<view class="has-floatr has-pdb-10">
					<button type="default" class="" @tap = "closeorder">
						<uni-icons class="has-mgr-12" type="undo" color="#F30C2C" size="20"></uni-icons>
						<text class="is-red-color">停止接单</text>
					</button>
				</view>
			</view>
		</view>
		<!-- 底部 ent-->
		<view>
		    <show-modal></show-modal>
		</view>
	</view>
</template>
 
<script>
	var _self;
	var ordertimer = null;
	import uniDrawer from '@/components/uni-drawer/uni-drawer.vue';
	import uniIcons from '@/components/uni-icons/uni-icons.vue';
	import minSwitch from '@/components/m-switch/m-switch.vue';
	import mhtLoader from '@/components/mht-loader/mht-loader.vue'; 
	export default {
		components: {
			uniDrawer,
			uniIcons,
			minSwitch,
			mhtLoader
		},
		data() {
			return {
				showLeft: false,
				showRight: false,
				foxtoken:'',
				foxcode:'',
				foxactive:'',
				memu:[],
				userinfo:[],
				user_money_can:0,
				fox_money_can:0,
				fox_user_jihuo:0,
				online:true,
				ma_lock:0,
				socketTask: null,
				// 确保websocket是打开状态
				is_open_socket: false,
				order:[],
				ma_type:0,
				ma_type_img:'',
				ma_id:0,
				uid:0,
				user_tel:'',
				diamond_money_can:0,
				today_num:0,
				today_num_wx:0,
				today_num_zfb:0,
				today_num_qq:0,
				today_num_bank:0,
				onlymecity:1,
				mycity:'',
				you_chose:'WX',
				showLoader:true
			}
		},
		onLoad() {
			_self = this;
			this.mycity = "选择同城（"+uni.getStorageSync('region')+"）";
			let music = uni.getStorageSync('music');
			if(music === true){
				this.OrderingAudio();
			}		
			this.getinfo();
			var matype = uni.getStorageSync('matype');
			if(matype==0){
				this.you_chose = 'WX';
			}else if(matype==1){
				this.you_chose = 'ZFB';
			}else if(matype==2){
				this.you_chose = 'QQ';
			}else if(matype==3){
				this.you_chose = 'BANK';
			}
			// console.log(matype)
			if(matype == ''){
				uni.showToast({
					title:'请先设置默认收款码',
					icon:'none',
					mask:true
				})
				setTimeout(function() {
				    uni.reLaunch({
				    	url:'../allcode/listcode'
				    })
				}, 1500)
				return;
			}
			
			this.memu = this.service.memu;
			this.connectSocketInit();
		},
		// 关闭websocket【必须在实例销毁之前关闭,否则会是underfined错误】
		beforeDestroy() {
			this.closeSocket();
		},
		computed: {
			neworder() {
				return this.order
			}
		},
		watch:{
			neworder: {
				handler: (val, olVal) => {
					let a = Object.keys(val).length;
					let b = Object.keys(olVal).length;
					let music = uni.getStorageSync('music');
					if(b==0 && a >0){
						if(music === true){
							_self.DingdanAudio();
						}
					}else if(b>0 && a >0){
						if(JSON.stringify(val) !== JSON.stringify(olVal)){
							if(music === true){
								_self.DingdanAudio();
							}
						}
					}
				},
				deep: true
			},
			'online':function(){
				this.LineAuto(this.online);
			}
		},
		methods: {
			getinfo(){
				let info = this.service.getfox();
				if(info[0]){
					this.foxtoken = info[0]['foxtoken'];
					uni.request({
						url: this.service.FOX_URL + 'diamond/get_userinfo_order',
						method:'POST',
						data: {
							user_key: this.foxtoken
						},
						dataType:'json',
						header:{
							'content-type':'application/x-www-form-urlencoded',
						},
						success: res => {
							// var rest = JSON.stringify(res);
							// console.log(rest)
							var rest = res.data;
							// console.log(rest.status)
							if(rest.status == 'success'){
								this.userinfo = rest.msg;
								this.today_num = this.userinfo['today_order'];
								this.today_num_wx = this.userinfo['today_order_wx'];
								this.today_num_zfb = this.userinfo['today_order_zfb'];
								this.today_num_qq = this.userinfo['today_order_qq'];
								this.today_num_bank = this.userinfo['today_order_bank'];
								this.ma_lock = this.userinfo['ma_lock'];
								this.uid= this.userinfo['user_id'];
								this.user_tel= this.userinfo['user_name'];
								this.diamond_money_can = this.userinfo['diamond_money_can'];
								this.user_money_can = this.userinfo['user_money_can'];
								if(this.userinfo['ma']){
									if(this.userinfo['ma']['ma_type']==0){
										this.ma_type = 'ma_wx';
										this.ma_type_img = '../../static/imgs/ma_wx.png';
									}else if(this.userinfo['ma']['ma_type']==1){
										this.ma_type = 'ma_zfb';
										this.ma_type_img = '../../static/imgs/ma_zfb.png';
									}else if(this.userinfo['ma']['ma_type']==2){
										this.ma_type = 'ma_qq';
										this.ma_type_img = '../../static/imgs/ma_qq.png';
									}else if(this.userinfo['ma']['ma_type']==3){
										this.ma_type = 'ma_bank';
										this.ma_type_img = '../../static/imgs/ma_bank.png';
									}
									this.ma_id = this.userinfo['ma']['id'];
								}
							}else if(rest.status == 'error'){
								uni.showToast({
									title:rest.msg,
									icon:'none',
									mask:true
								})
							}else{
								uni.showToast({
									title:rest.msg,
									icon:'none',
									mask:true
								})
							}
						}
					})
				}else{
					uni.reLaunch({
						url:'../logon/login'
					})
				}
			},
			show(e) {
				if (e === 'left') {
					this.showLeft = true
				}
			},
			closeDrawer(e) {
				if (e === 'left') {
					this.showLeft = false
				}
			},
			// 进入这个页面的时候创建websocket连接【整个页面随时使用】
			connectSocketInit() {
				//uni.clearStorageSync();
				// 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
				this.socketTask = uni.connectSocket({
					// 【非常重要】必须确保你的服务器是成功的,如果是手机测试千万别使用ws://127.0.0.1:9099【特别容易犯的错误】
					url: this.service.FOX_SOKET,
					success(data) {
						console.log("websocket连接成功");
					},
				});
 
				// 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
				this.socketTask.onOpen((res) => {
					console.log("WebSocket连接正常打开中...！");
					let matype = uni.getStorageSync('matype');
					// console.log(matype)
					this.is_open_socket = true;
					this.online = true;
					ordertimer = setInterval(()=>{
						// 注：只有连接正常打开中 ，才能正常成功发送消息
						let msg = {'type':'order','ma_type':matype,'user_key':this.foxtoken};
						msg = JSON.stringify(msg);
						// console.log(msg)
						this.socketTask.send({
							data: msg,
							async success() {
								console.log("order消息发送成功");
							},
						});
					},5000)					
					// 注：只有连接正常打开中 ，才能正常收到消息
					this.socketTask.onMessage((res) => {
						console.log("收到服务器内容order");
						var rest = JSON.parse(res.data);
						// console.log(rest)
						if(rest.type == 'order'){
							if(rest.data.list.length >0){
								this.showLoader = false;
								this.order = rest.data.list;
							}else{
								this.showLoader = true;
								this.order = [];
							}
							this.today_num = rest.today_num;
						}else if(rest.type == 'grab'){
							this.order.splice(rest.index, 1);
							if(rest.msg){
								this.user_money_can = parseFloat(rest.money_can).toFixed(2);
								// uni.showToast({title:'抢单成功',icon:'none'})
								let grabid = rest.id;
								uni.navigateTo({
									url:'./orderdo?id='+grabid
								})
							}else{
								uni.showToast({title:'抢单失败',icon:'none'})
							}
						}else if(rest.type == 'none'){
							this.order = [];
							this.showLoader = true;
							this.today_num = rest.today_num;
						}else if(rest.type == 'nograb'){
							this.$showModal({
								title: '提示',
								content: '可用余额须大于'+this.diamond_money_can+'DC，方可抢单',
								cancelText:'放弃',
								confirmText:'买币',
								success: function (res) {
									if (res.confirm) {
										uni.navigateTo({
											url:'../account/buydc'
										})
									}
								}
							})
						}
						// let rets = JSON.stringify(res.data);
						// console.log(rets)
					});
				})
				// 这里仅是事件监听【如果socket关闭了会执行】
				this.socketTask.onClose(() => {
					_self.online = false;
				})
				this.socketTask.onError(function(){
					_self.online = false;
				})
			},
			//停止接单
			closeorder() {
				clearInterval(ordertimer);
				setTimeout(function() {
					uni.navigateTo({
						url:'/pages/index/index'
					})
				}, 1000)
			},
			// 关闭websocket【离开这个页面的时候执行关闭】
			closeSocket() {
				this.socketTask.close({
					success(res) {
						this.is_open_socket = false;
					}
				})
			},
			grab:function(id,index){
				if(parseInt(this.user_money_can) < parseInt(this.diamond_money_can)){
					this.$showModal({
						title: '提示',
						content: '可用余额须大于'+this.diamond_money_can+'DC，方可抢单',
						cancelText:'放弃',
						confirmText:'买币',
						success: function (res) {
							if (res.confirm) {
								uni.navigateTo({
									url:'../account/buydc'
								})
							}
						}
					})
				}else{
					if (this.is_open_socket) {
						// websocket的服务器的原理:发送一次消息,同时返回一组数据【否则服务器会进去死循环崩溃】
						var message = {'type':'grab','order_id':id,'ma_id':this.ma_id,'ma_type':this.ma_type,'uid':this.uid,'user_tel':this.user_tel,'user_key':this.foxtoken,'index':index};
						this.socketTask.send({
							data: JSON.stringify(message),
							async success() {
								console.log("消息发送成功");
							},
						});
					}
				}
			},
			ordering(){
				clearInterval(ordertimer);
				uni.reLaunch({
					url:'./order_ing'
				})
			}
		},
		onUnload: function() {
			if(ordertimer) {  
				clearInterval(ordertimer);  
				ordertimer = null;  
			}
		}
	}
</script>

<style>
	.spinner {
		margin-left: 20upx;
	    display: inline-block;
	}
	.spinner > view {
	    width: 28upx;
	    height: 28upx;
	    background-color:#2A62FF;
	    border-radius: 100%;
	    display: inline-block;
	    -webkit-animation: bouncedelay 1.6s infinite ease-in-out;
	    animation: bouncedelay 1.6s infinite ease-in-out;
	    -webkit-animation-fill-mode: both;
	    animation-fill-mode: both;
	}
	.spinner .bounce1 {
		margin-right:12upx;
	    -webkit-animation-delay: -0.64s;
	    animation-delay: -0.64s;
	}
	.spinner .bounce2 {
		margin-right:12upx;
	    -webkit-animation-delay: -0.32s;
	    animation-delay: -0.32s;
	}
	.spinner .bounce3 {
		margin-right:12upx;
	    -webkit-animation-delay: -0.16s;
	    animation-delay: -0.16s;
	}
	.spinner .bounce4 {
		margin-right:12upx;
	    -webkit-animation-delay: -0.16s;
	    animation-delay: -0.16s;
	}
	.spinner .bounce5 {
		margin-right:12upx;
	    -webkit-animation-delay: -0.16s;
	    animation-delay: -0.16s;
	}
	@-webkit-keyframes bouncedelay {
	    0%, 100% {
	        -webkit-transform: scale(0.0)
	    }
	    50% {
	        -webkit-transform: scale(1.0)
	    }
	}
	@keyframes bouncedelay {
	    0%, 100% {
	        transform: scale(0.0);
	        -webkit-transform: scale(0.0);
	    }
	    50% {
	        transform: scale(1.0);
	        -webkit-transform: scale(1.0);
	    }
	}
	.pd-bottome{padding-bottom: 80upx;background: #F9F9F9;}
	.pie {
	  display: inline-block;
	  position: relative;
	  width: 90upx;
	  height: 90upx;
	  border-radius: 50%;
	  background: #F30C2C;
	  background-image: linear-gradient(to right, transparent 50%, #FFFF33 0);
	  color: transparent;
	  text-align: center;
	  border: 1px solid #FF8800;
	}
	.pie::before {
	  content: '';
	  position: absolute;
	  top: 0; left: 50%;
	  width: 50%; height: 100%;
	  border-radius: 0 100% 100% 0 / 50%;
	  background-color: inherit;
	  transform-origin: left;
	  animation: spin 15s linear infinite, bg 30s step-end infinite;
	}
	@keyframes spin {
	  to { transform: rotate(.5turn); }
	}
	@keyframes bg {
	  50% { background: #FFFF00; }
	}   
	.pie-inner {
	    position: absolute;
	    top: 9%;
	    bottom: 9%;
	    left: 9%;
	    right: 9%;
	    background-color: #FF8800;
	    border-radius: 50%;
	    overflow: hidden;
	    display: flex;
	    align-items: center;
	    justify-content: center;
	    color: #FFFFBB;
	  }
	  .ma-box image {width:100upx;height: 100upx;}
	  .ma-order{background: #FFFFFF;border-top: 2upx solid #F0F0F0;}
</style>